// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let loginSection, mainContent, loginForm, logoutBtn;
let refreshLocationStatusBtn, refreshLocationMaterialBtn, refreshLocationEnableDisableBtn;
let locationStatusView, locationMaterialView, locationEnableDisableView;
let showEmptyLocations, showOccupiedLocations, showDisabledLocations, showEnabledLocations, showDisabledLocationsFilter;
let materialFilter;
let enableSelectedBtn, disableSelectedBtn;
let locationCodeFilter, aisleFilter, rowFilter, columnFilter, levelFilter;
let applyFilterBtn, resetFilterBtn;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 当前选中的货位
let selectedLocations = [];

// 仓库配置信息
let warehouseConfig = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadWarehouseConfig().then(() => {
            loadAllData();
        });
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 视图元素
    locationStatusView = document.getElementById('locationStatusView');
    locationMaterialView = document.getElementById('locationMaterialView');
    locationEnableDisableView = document.getElementById('locationEnableDisableView');

    // 按钮元素
    refreshLocationStatusBtn = document.getElementById('refreshLocationStatusBtn');
    refreshLocationMaterialBtn = document.getElementById('refreshLocationMaterialBtn');
    refreshLocationEnableDisableBtn = document.getElementById('refreshLocationEnableDisableBtn');
    enableSelectedBtn = document.getElementById('enableSelectedBtn');
    disableSelectedBtn = document.getElementById('disableSelectedBtn');
    applyFilterBtn = document.getElementById('applyFilterBtn');
    resetFilterBtn = document.getElementById('resetFilterBtn');

    // 输入元素
    showEmptyLocations = document.getElementById('showEmptyLocations');
    showOccupiedLocations = document.getElementById('showOccupiedLocations');
    showDisabledLocations = document.getElementById('showDisabledLocations');
    showEnabledLocations = document.getElementById('showEnabledLocations');
    showDisabledLocationsFilter = document.getElementById('showDisabledLocationsFilter');
    materialFilter = document.getElementById('materialFilter');
    locationCodeFilter = document.getElementById('locationCodeFilter');
    aisleFilter = document.getElementById('aisleFilter');
    rowFilter = document.getElementById('rowFilter');
    columnFilter = document.getElementById('columnFilter');
    levelFilter = document.getElementById('levelFilter');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // 刷新货位状态视图按钮
    if (refreshLocationStatusBtn) {
        refreshLocationStatusBtn.addEventListener('click', handleRefreshLocationStatus);
    }
    
    // 刷新货位物料视图按钮
    if (refreshLocationMaterialBtn) {
        refreshLocationMaterialBtn.addEventListener('click', handleRefreshLocationMaterial);
    }
    
    // 刷新货位启用/禁用视图按钮
    if (refreshLocationEnableDisableBtn) {
        refreshLocationEnableDisableBtn.addEventListener('click', handleRefreshLocationEnableDisable);
    }
    
    // 启用选中按钮
    if (enableSelectedBtn) {
        enableSelectedBtn.addEventListener('click', handleEnableSelected);
    }
    
    // 禁用选中按钮
    if (disableSelectedBtn) {
        disableSelectedBtn.addEventListener('click', handleDisableSelected);
    }
    
    // 应用筛选按钮
    if (applyFilterBtn) {
        applyFilterBtn.addEventListener('click', handleApplyFilter);
    }
    
    // 重置筛选按钮
    if (resetFilterBtn) {
        resetFilterBtn.addEventListener('click', handleResetFilter);
    }
    
    // 货位显示选项变化
    if (showEmptyLocations) {
        showEmptyLocations.addEventListener('change', handleLocationFilterChange);
    }
    
    if (showOccupiedLocations) {
        showOccupiedLocations.addEventListener('change', handleLocationFilterChange);
    }
    
    if (showDisabledLocations) {
        showDisabledLocations.addEventListener('change', handleLocationFilterChange);
    }
    
    if (showEnabledLocations) {
        showEnabledLocations.addEventListener('change', handleEnableDisableFilterChange);
    }
    
    if (showDisabledLocationsFilter) {
        showDisabledLocationsFilter.addEventListener('change', handleEnableDisableFilterChange);
    }
    
    // 物料筛选输入
    if (materialFilter) {
        materialFilter.addEventListener('input', handleMaterialFilterChange);
    }
    
    // 模块导航
    setupModuleNavigation();
    
    console.log('事件监听器绑定完成');
}

// 设置模块导航
function setupModuleNavigation() {
    const navLinks = document.querySelectorAll('.module-nav a');
    const sections = document.querySelectorAll('.module-section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            sections.forEach(s => s.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            const targetSection = document.querySelector(this.getAttribute('href'));
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadWarehouseConfig().then(() => {
                loadAllData();
            });
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 加载仓库配置信息
function loadWarehouseConfig() {
    if (!authToken) return Promise.resolve();
    
    return fetch(`${API_BASE_URL}/locations/config`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            warehouseConfig = data.data;
            console.log('仓库配置加载成功:', warehouseConfig);
            // 更新筛选器选项
            updateFilterOptions();
        }
    })
    .catch(error => {
        console.error('加载仓库配置失败:', error);
    });
}

// 更新筛选器选项
function updateFilterOptions() {
    if (!warehouseConfig || !aisleFilter) return;
    
    // 更新巷道筛选选项
    aisleFilter.innerHTML = '<option value="">全部</option>';
    warehouseConfig.aisles.forEach(aisle => {
        const option = document.createElement('option');
        option.value = aisle.code;
        option.textContent = aisle.code + '号巷道';
        aisleFilter.appendChild(option);
    });
    
    // 更新排、列、层筛选选项（使用第一个巷道的配置作为示例）
    if (warehouseConfig.aisles.length > 0) {
        const firstAisle = warehouseConfig.aisles[0];
        
        // 更新排筛选选项
        if (rowFilter) {
            rowFilter.innerHTML = '<option value="">全部</option>';
            for (let i = 1; i <= firstAisle.rows; i++) {
                const option = document.createElement('option');
                option.value = i.toString().padStart(2, '0');
                option.textContent = i.toString().padStart(2, '0');
                rowFilter.appendChild(option);
            }
        }
        
        // 更新列筛选选项
        if (columnFilter) {
            columnFilter.innerHTML = '<option value="">全部</option>';
            for (let i = 1; i <= firstAisle.columns; i++) {
                const option = document.createElement('option');
                option.value = i.toString().padStart(2, '0');
                option.textContent = i.toString().padStart(2, '0');
                columnFilter.appendChild(option);
            }
        }
        
        // 更新层筛选选项
        if (levelFilter) {
            levelFilter.innerHTML = '<option value="">全部</option>';
            for (let i = 1; i <= firstAisle.levels; i++) {
                const option = document.createElement('option');
                option.value = i.toString().padStart(2, '0');
                option.textContent = i.toString().padStart(2, '0');
                levelFilter.appendChild(option);
            }
        }
    }
}

// 处理刷新货位状态视图
function handleRefreshLocationStatus() {
    loadLocationStatusView();
}

// 处理刷新货位物料视图
function handleRefreshLocationMaterial() {
    loadLocationMaterialView();
}

// 处理刷新货位启用/禁用视图
function handleRefreshLocationEnableDisable() {
    loadLocationEnableDisableView();
}

// 处理启用选中
function handleEnableSelected() {
    if (selectedLocations.length === 0) {
        alert('请先选择要启用的货位');
        return;
    }
    
    if (confirm(`确定要启用选中的${selectedLocations.length}个货位吗？`)) {
        updateLocationStatusBatch(selectedLocations, 'enabled');
    }
}

// 处理禁用选中
function handleDisableSelected() {
    if (selectedLocations.length === 0) {
        alert('请先选择要禁用的货位');
        return;
    }
    
    if (confirm(`确定要禁用选中的${selectedLocations.length}个货位吗？`)) {
        updateLocationStatusBatch(selectedLocations, 'disabled');
    }
}

// 处理应用筛选
function handleApplyFilter() {
    loadLocationEnableDisableView();
}

// 处理重置筛选
function handleResetFilter() {
    // 重置筛选条件
    if (locationCodeFilter) locationCodeFilter.value = '';
    if (aisleFilter) aisleFilter.value = '';
    if (rowFilter) rowFilter.value = '';
    if (columnFilter) columnFilter.value = '';
    if (levelFilter) levelFilter.value = '';
    
    loadLocationEnableDisableView();
}

// 处理货位筛选变化
function handleLocationFilterChange() {
    loadLocationStatusView();
}

// 处理启用/禁用筛选变化
function handleEnableDisableFilterChange() {
    loadLocationEnableDisableView();
}

// 处理物料筛选变化
function handleMaterialFilterChange() {
    loadLocationMaterialView();
}

// 加载所有数据
function loadAllData() {
    loadLocationStatusView();
    loadLocationMaterialView();
    loadLocationEnableDisableView();
}

// 加载货位状态视图
function loadLocationStatusView() {
    if (!authToken) return;
    
    if (!locationStatusView) return;
    
    // 模拟货位数据
    const locations = generateMockLocations();
    
    // 应用筛选器
    const showEmpty = showEmptyLocations ? showEmptyLocations.checked : true;
    const showOccupied = showOccupiedLocations ? showOccupiedLocations.checked : true;
    const showDisabled = showDisabledLocations ? showDisabledLocations.checked : true;
    
    const filteredLocations = locations.filter(location => {
        if (location.status === 'empty' && !showEmpty) return false;
        if (location.status === 'occupied' && !showOccupied) return false;
        if (location.status === 'disabled' && !showDisabled) return false;
        return true;
    });
    
    renderLocationStatusView(filteredLocations);
}

// 生成模拟货位数据
function generateMockLocations() {
    const locations = [];
    for (let i = 1; i <= 20; i++) {
        // 随机生成状态：empty, occupied, disabled
        const statusOptions = ['empty', 'occupied', 'disabled'];
        const status = statusOptions[Math.floor(Math.random() * statusOptions.length)];
        
        locations.push({
            id: i,
            location: `A-${Math.floor((i-1)/5)+1}-${((i-1)%5)+1}`,
            status: status,
            goodsName: status === 'empty' ? '' : `货物${i}`,
            quantity: status === 'empty' ? 0 : Math.floor(Math.random() * 100) + 1
        });
    }
    return locations;
}

// 渲染货位状态视图
function renderLocationStatusView(locations) {
    if (!locationStatusView) return;
    
    let html = '<div class="location-grid">';
    locations.forEach(location => {
        let statusClass = location.status;
        html += `
            <div class="location-item ${statusClass}">
                <div class="location-id">${location.location}</div>
                <div class="location-info">
                    ${location.status === 'empty' ? 
                        '<div class="location-status">空闲</div>' : 
                        location.status === 'disabled' ?
                        '<div class="location-status">禁用</div>' :
                        `<div class="location-goods">${location.goodsName}</div>
                         <div class="location-quantity">数量: ${location.quantity}</div>`}
                </div>
            </div>
        `;
    });
    html += '</div>';
    
    locationStatusView.innerHTML = html;
}

// 加载货位物料视图
function loadLocationMaterialView() {
    if (!authToken) return;
    
    if (!locationMaterialView) return;
    
    // 获取筛选关键字
    const keyword = materialFilter ? materialFilter.value : '';
    
    // 模拟物料数据
    const materials = generateMockMaterials();
    
    // 应用筛选器
    const filteredMaterials = keyword ? 
        materials.filter(material => material.name.includes(keyword)) : 
        materials;
    
    renderLocationMaterialView(filteredMaterials);
}

// 生成模拟物料数据
function generateMockMaterials() {
    return [
        { id: 1, name: '原材料A', locations: ['A-1-1', 'A-1-2', 'A-2-1'], totalQuantity: 150 },
        { id: 2, name: '原材料B', locations: ['A-1-3', 'A-2-2'], totalQuantity: 80 },
        { id: 3, name: '半成品C', locations: ['A-2-3', 'A-3-1'], totalQuantity: 120 },
        { id: 4, name: '成品D', locations: ['A-3-2', 'A-3-3', 'A-4-1'], totalQuantity: 200 },
        { id: 5, name: '包装材料E', locations: ['A-4-2', 'A-4-3'], totalQuantity: 90 }
    ];
}

// 渲染货位物料视图
function renderLocationMaterialView(materials) {
    if (!locationMaterialView) return;
    
    let html = '<div class="material-list">';
    materials.forEach(material => {
        html += `
            <div class="material-item">
                <div class="material-name">${material.name}</div>
                <div class="material-quantity">总数量: ${material.totalQuantity}</div>
                <div class="material-locations">
                    <strong>存储货位:</strong> ${material.locations.join(', ')}
                </div>
            </div>
        `;
    });
    html += '</div>';
    
    locationMaterialView.innerHTML = html;
}

// 加载货位启用/禁用视图
function loadLocationEnableDisableView() {
    if (!authToken) return;
    
    if (!locationEnableDisableView) return;
    
    // 构建查询参数
    const queryParams = {};
    
    if (locationCodeFilter && locationCodeFilter.value) {
        queryParams.locationCode = locationCodeFilter.value;
    }
    
    if (aisleFilter && aisleFilter.value) {
        queryParams.aisle = aisleFilter.value;
    }
    
    if (rowFilter && rowFilter.value) {
        queryParams.row = rowFilter.value;
    }
    
    if (columnFilter && columnFilter.value) {
        queryParams.column = columnFilter.value;
    }
    
    if (levelFilter && levelFilter.value) {
        queryParams.level = levelFilter.value;
    }
    
    // 应用启用/禁用筛选
    const showEnabled = showEnabledLocations ? showEnabledLocations.checked : true;
    const showDisabled = showDisabledLocationsFilter ? showDisabledLocationsFilter.checked : true;
    
    if (showEnabled && showDisabled) {
        // 不添加状态筛选，显示所有
    } else if (showEnabled) {
        queryParams.status = 'enabled';
    } else if (showDisabled) {
        queryParams.status = 'disabled';
    } else {
        // 都不选，显示空
        renderLocationEnableDisableView([]);
        return;
    }
    
    // 模拟货位数据
    const locations = generateMockEnableDisableLocations();
    
    // 应用筛选器
    const filteredLocations = locations.filter(location => {
        // 应用查询参数筛选
        if (queryParams.locationCode && !location.location_code.includes(queryParams.locationCode)) return false;
        if (queryParams.aisle && location.aisle !== queryParams.aisle) return false;
        if (queryParams.row && location.row !== queryParams.row) return false;
        if (queryParams.column && location.column !== queryParams.column) return false;
        if (queryParams.level && location.level !== queryParams.level) return false;
        if (queryParams.status && location.status !== queryParams.status) return false;
        return true;
    });
    
    renderLocationEnableDisableView(filteredLocations);
}

// 生成模拟货位启用/禁用数据
function generateMockEnableDisableLocations() {
    const locations = [];
    for (let i = 1; i <= 20; i++) {
        // 随机生成状态：enabled, disabled
        const status = Math.random() > 0.5 ? 'enabled' : 'disabled';
        
        locations.push({
            id: i,
            location_code: `WH01-A-${Math.floor((i-1)/5)+1}-${((i-1)%5)+1}`,
            aisle: 'A',
            row: Math.floor((i-1)/5)+1,
            column: ((i-1)%5)+1,
            level: 1,
            status: status
        });
    }
    return locations;
}

// 渲染货位启用/禁用视图
function renderLocationEnableDisableView(locations) {
    if (!locationEnableDisableView) return;
    
    // 清空选中列表
    selectedLocations = [];
    
    let html = `
        <div class="location-enable-disable-grid">
            <div class="location-enable-disable-header">
                <div class="header-cell">选择</div>
                <div class="header-cell">货位编码</div>
                <div class="header-cell">巷道</div>
                <div class="header-cell">排</div>
                <div class="header-cell">列</div>
                <div class="header-cell">层</div>
                <div class="header-cell">状态</div>
                <div class="header-cell">操作</div>
            </div>
    `;
    
    locations.forEach(location => {
        const statusText = location.status === 'enabled' ? '启用' : '禁用';
        const statusClass = location.status === 'enabled' ? 'status-enabled' : 'status-disabled';
        
        html += `
            <div class="location-enable-disable-row" data-id="${location.id}">
                <div class="cell">
                    <input type="checkbox" class="location-checkbox" data-id="${location.id}">
                </div>
                <div class="cell">${location.location_code}</div>
                <div class="cell">${location.aisle}</div>
                <div class="cell">${location.row}</div>
                <div class="cell">${location.column}</div>
                <div class="cell">${location.level}</div>
                <div class="cell">
                    <span class="status-badge ${statusClass}">${statusText}</span>
                </div>
                <div class="cell">
                    <button class="btn-primary btn-small ${location.status === 'enabled' ? 'btn-secondary' : 'btn-primary'}" 
                            onclick="toggleLocationStatus(${location.id}, '${location.status === 'enabled' ? 'disabled' : 'enabled'}')">
                        ${location.status === 'enabled' ? '禁用' : '启用'}
                    </button>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    
    locationEnableDisableView.innerHTML = html;
    
    // 绑定复选框事件
    document.querySelectorAll('.location-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const id = parseInt(this.getAttribute('data-id'));
            if (this.checked) {
                if (!selectedLocations.includes(id)) {
                    selectedLocations.push(id);
                }
            } else {
                selectedLocations = selectedLocations.filter(locationId => locationId !== id);
            }
            console.log('选中的货位:', selectedLocations);
        });
    });
}

// 切换货位状态
function toggleLocationStatus(id, newStatus) {
    updateLocationStatusBatch([id], newStatus);
}

// 批量更新货位状态
function updateLocationStatusBatch(ids, status) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/locations/status/batch`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ ids, status })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            // 重新加载视图
            loadLocationEnableDisableView();
            loadLocationStatusView();
        } else {
            alert('更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新货位状态失败:', error);
        alert('更新货位状态失败');
    });
}